var uid = 1;
var username,name;
var countdown = 60; //计时60s
var countTimer;
var org = [];
var stype = -1;
var parentOrg = [];
var limit =30;
layui.use(['table', 'form', 'laydate'], function() {
	var table = layui.table,
		$ = layui.jquery,
		layer = layui.layer,
		form = layui.form,
		laydate = layui.laydate;

	//时间选择器
	laydate.render({
		elem: '.startTime',
		type: 'datetime'
	});
	laydate.render({
		elem: '.endTime',
		type: 'datetime'
	});

	//初始化查询时间
	$(".searchTools .startTime").val(getNowTime());
	$(".searchTools .endTime").val(getNextTime());
	//初始化查询参数
	var options = {
		offset: 0,
		limit: limit,
		pageIndex: 1,
		status: $(".searchTools .status").val()
	};
	var originOptions;
	var tempOptions = options;
	/**初始化部门**/
	initOrigin();
	loadData(options);

	/**同步OA通讯录**/
	$(".searchTools .syn-user-btn").on("click", function () {
		var loading = layer.load(1);
		$.ajax({
			type: "POST",
			url: "/sys_user/syn/user",
			async: true,
			dataType: 'json',
			timeout: 5000,
			success: function(res) {
				layer.close(loading);
				// console.log(res);
				layer.msg(res.msg);
				loadData(tempOptions);
			},
			error: function(res) {
				layer.msg("请求失败，请稍后再试！");
				layer.close(loading);
				return;
			},
			complete: function(XMLHttpRequest, status) {
				if(status == 'timeout') {
					layer.msg("请求超时，请稍后再试！");
					layer.close(loading);
					return;
				}

			}
		});
	});
	$(document).keyup(function(event){
		if(event.keyCode ==13){
			$(".searchTools .search-btn").trigger("click");
		}
	});

	//查询
	$(".searchTools .search-btn").on("click", function() {
		var username = $.trim($(".searchTools .username").val());
		var name = $.trim($(".searchTools .name").val());
		var status = $(".searchTools .status").val();
		var datas = {
				offset: 0,
				limit: limit,
				pageIndex: 1
			};
		if(!isNull(username))
			datas['username'] = username;
		
		if(!isNull(name))
			datas['name'] = name;
		if(!isNull(status))
			datas['status'] = parseInt($(".searchTools .status").val());

		tempOptions = datas;
		loadData(datas);
	})

	//点击禁用
	$(".userList").on("click", ".del-btn", function() {
		var options = {id: parseInt($(this).attr('data-id')),status: 1};
		updateUser(options, "/sys_user/update/status");
	});
	//点击启用
	$(".userList").on("click", ".on-btn", function() {
		var options = {id: parseInt($(this).attr('data-id')),status: 0};
		updateUser(options, "/sys_user/update/status");
	});

	//点击关联部门
	$(".userList").on("click", ".concat-btn", function() {
		$(".concatModal").show();
		var options = {orgId: parseInt($(this).attr('data-id'))};
		$('.concatModal .userAndOriginTitle').html($(this).attr('data-name') + '==>关联部门列表');

		uid = parseInt($(this).attr('data-id'));
		var options = {uid: uid,type: 2};
		originOptions = options;
		loadOrigin(options);
	});

	/**点击关联查询**/
	$('.originSearchTools .search-btn').on('click', function () {
		var type = $('.originSearchTools .type').val();
		var options = {uid: uid};
		if (!isNull(type))
			options['type'] = type;
		else
			options['type'] = -1;

		originOptions = options;
		loadOrigin(options);
	});

	//点击添加
	$(".searchTools .addUser").on("click", function() {
		$(".addUserModal").show();
	});
	$(".addUserModal .close").on("click", function() {
		$(".addUserModal").hide();
		$(".addUserModal input").val("");
		$(".addUserModal .getMessage").val("发送验证码").removeClass("btn-disabled");
		$(".addUserModal .getMessage").attr("disabled", false);
		countdown = 60;
		clearTimeout(countTimer);
	})
	//点击添加提交
	$(".addUserModal .btn-submit").on("click", function() {
		var username = $.trim($(".addUserModal .username").val());
		var password = $.trim($(".addUserModal .password").val());
		var name = $.trim($(".addUserModal .name").val());
		var status = $.trim($(".addUserModal .status").val());
		var type = $.trim($(".addUserModal .type").val());
		var email = $.trim($(".addUserModal .email").val());
		var phone = $.trim($(".addUserModal .phone").val());
		var nickname = $.trim($(".addUserModal .nickname").val());
		//判断密码格式
		var pwdReg = /^[A-Za-z0-9]{6,16}$/;
		if(username == '' || username == null || username == undefined) {
			layer.msg("用户名不能为空！");
			return;
		} else if(username.length < 6 || username.length > 16) {
			layer.msg("用户名长度为 6-16 位！");
			return;
		} else if(!pwdReg.test(username)) {
			layer.msg("用户名格式位  6-16 位字母、数字！");
			return;
		}

		//判断密码
		if(isNull(password)) {
			layer.msg("密码不能为空");
			return;
		} else if(password.length < 6 || password.length > 16) {
			layer.msg("密码长度为 6-16 位！");
			return;
		} else if(!pwdReg.test(password)) {
			layer.msg("密码格式位  6-16 位字母、数字！");
			return;
		}
		var options = {
			username: username,
			password: password
		}

		if(!isNull(name))
			options['name'] = name;

		if(!isNull(type))
			options['type'] = parseInt(type);

		if(!isNull(phone))
			options['phone'] = phone;

		if(!isNull(email))
			options['email'] = email;

		if(!isNull(status))
			options['status'] = parseInt(status);

		if(!isNull(nickname))
			options['nickname'] = nickname;

		var loading = layer.load(1);
		$.ajax({
			type: "put",
			url: "/sys_user/save",
			async: true,
			dataType: 'json',
			timeout: 5000,
			data: options,
			success: function(res) {
				layer.close(loading);
				// console.log(res);
				if(res.code == 0) {
					layer.msg(res.msg);
					$(".addUserModal").hide();
					$(".addUserModal input").val("");
					$(".addUserModal select").val("");
					form.render();
					loadData(tempOptions);
				} else {
					layer.msg(res.msg);
					return;
				}
			},
			error: function(res) {
				layer.msg("请求失败，请稍后再试！");
				layer.close(loading);
				return;
			},
			complete: function(XMLHttpRequest, status) {
				if(status == 'timeout') {
					layer.msg("请求超时，请稍后再试！");
					layer.close(loading);
					return;
				}
			}
		});
	})
	//修改按钮
	$(".userList").on("click", ".set-btn", function() {
		uid = $(this).attr('data-id');
		$(".updateModal").show();
		$(".updateModal .username").val($(this).attr('data-username'));
		$(".updateModal .name").val($(this).attr('data-name'));
		$(".updateModal .nickname").val($(this).attr('data-nickname'));
		$(".updateModal .phone").val($(this).attr('data-phone'));
	})

	//点击订阅消息
	$(".userList").on("click", ".sub-btn", function() {
		uid = $(this).attr('data-id');
		username = $(this).attr('data-username');
		name = $(this).attr('data-name');
		var option = {};
		subscribeData(option, "/report/subscribe/type");
		$(".subModal").show();
	});

	/**关闭修改弹出框**/
	$(".updateModal .close").on("click", function() {
		$(".updateModal").hide();
		$(".updateModal input").val("");
	});
	/**关闭关联部门弹出框**/
	$(".concatModal .close").on("click", function() {
		$(".concatModal").hide();
		loadData(tempOptions);
	});

	/**关闭关联部门弹出框**/
	$(".subModal .close").on("click", function() {
		$(".subModal").hide();
	});
    $(".orgModal .close").on("click", function() {
        $(".orgModal").hide();
    });
    $(".orgGpsModal .close").on("click", function() {
		$(".orgGpsModal").hide();
	});
	//用户修改
	$(".updateModal .btn-submit").on("click", function() {
		var password =$.trim($(".updateModal .password").val());
		var name =$.trim($(".updateModal .name").val());
		var options = {
			id: uid,
			name: name,
			password: password
		};
		updateUser(options, '/sys_user/update');
	});
	//订阅早报
	$('.orgSubList').on('click', '.btn-addOrgSub', function () {
		var orgId = $(this).attr('data-orgId');
		var orgName = $(this).attr('data-orgName');
		var option = {
			type: stype,
			uid: uid,
			username: username,
			name: name,
			orgName:orgName,
			orgId:orgId
		};
		saveSubscribe(option, "/report/subscribe/save", 1);
	});
	//订阅GPS预警
	$('.orgGpsSubList').on('click', '.btn-addOrgSub', function () {
		var orgId = $(this).attr('data-orgId');
		var orgName = $(this).attr('data-orgName');
		var option = {
			type: stype,
			uid: uid,
			username: username,
			name: name,
			orgName:orgName,
			orgId:orgId
		};
		saveSubscribe(option, "/gps/waring/subscribe/save", 2);
	});
	//添加订阅记录
	$('.subModal').on('click', '.btn-addSub', function () {
		$('.orgModal').show();
		stype = parseInt($(this).attr('data-id'));
		var option = {uid:uid,type:stype};
		loadSubOrigin(option, "/report/subscribe/origin", 1);
	});
	//添加GPS订阅记录
	$('.subModal').on('click', '.btn-addGpsSub', function () {
		$('.orgGpsModal').show();
		stype = parseInt($(this).attr('data-id'));
		var option = {uid:uid,type:stype};
		loadSubOrigin(option, "/gps/waring/origin", 2);
	});

	//删除关联
	$(".concatModal").on("click", ".btn-delConcat", function() {
		var orgId = $(this).attr("data-id");
		var uid = $(this).attr('data-uid');
		var options = {uid: parseInt(uid), orgId: parseInt(orgId)};
		var url = '/sys_user/delete/relation/' + uid;
		relationData(options, url);
	});

	//添加关联
	$(".concatModal").on("click", ".btn-addConcat", function() {
		var orgId = $(this).attr("data-id");
		var uid = $(this).attr('data-uid');
		var options = {uid: parseInt(uid), orgId: parseInt(orgId)};
		var url = '/sys_user/add/relation/' + uid;
		relationData(options, url);
	});

	//获取用户列表
	function loadData(options) {
		var loading = layer.load(1);
		$.ajax({
			type: "POST",
			url: "/sys_user/list",
			async: true,
			dataType: 'json',
			timeout: 5000,
			data: options,
			success: function(res) {
				layer.close(loading);
				// console.log(res);
				if(res.code == 0) {
					$(".userListPage").page({
						total: res.data.total, //总条数
						pageIndex: options.pageIndex, //当前页
						pageSize: options.limit, //每页显示
						showInfo: true, //是否显示记录信息
						prevBtnText: '上一页',
						nextBtnText: "下一页",
						infoFormat: '总共{total}条记录,每页显示{size}条记录,共{count}页' //定义记录信息格式
					}).on("pageClicked", function(event, pageIndex) {
						//分页点击
						options.offset = options.offset - (options.pageIndex-pageIndex )* options.limit;
						options.pageIndex = pageIndex;
						loadData(options);
					});

					//具体数据列表
					var data = res.data.records;
					if(data == null || data.length <= 0) {
						$(".userList .tableList").empty().append("<tr><td colspan='8'>暂无数据</td></tr>");
						return;
					}
					var html = '';
					$.each(data, function(index, val) {
						var statusBtn = '';
						var statusStr = '正常';
						var typeStr = '普通用户';
						if (val.status == 0)
							statusStr = '正常';
						else if (val.status == 1)
							statusStr = '禁用';
						else
							statusStr = '删除';
						if (val.type == 1)
							typeStr = '系统用户';
						else
							typeStr = '普通用户';

						if (val.status == 0)
							statusBtn = '<a href="javascript:void(0)" data-id="' + val.id + '" class="layui-btn del-btn" style="background-color:#d9534f"><img src="/static/console/img/off.png" />禁用</a>';
						else
							statusBtn = '<a href="javascript:void(0)" data-id="' + val.id + '" class="layui-btn on-btn" style="background-color:#1890ff"><img src="/static/console/img/on.png" />启用</a>';
						var concatBtn = '<a href="javascript:void(0)" data-name="' + val.name + '" data-id="' + val.id + '" class="layui-btn concat-btn" style="background-color:#1890ff"><img src="/static/console/img/concat.png" />关联部门</a>';
						var subBtn = '<a href="javascript:void(0)" data-username="' + val.username +'" data-name="' + val.name + '" data-id="' + val.id + '" class="layui-btn sub-btn" style="background-color:#1890ff"><img src="/static/console/img/concat.png" />订阅消息</a>';
						var btn = '<a href="javascript:void(0)" data-username="' + val.username + '" data-password="' + val.password + '" data-nickname="' + val.nickname
							+ '" data-name="' + val.name + '" data-status="' + val.status + '" data-type="' + val.type
							+ '" data-phone="' + val.phone + '" class="layui-btn set-btn" ' +
							'style="background-color:#1890ff"><img src="/static/console/img/edit.png" />修改</a>' + statusBtn + concatBtn + subBtn;

						html += "<tr><td>" + convertVal(val.username) + "</td><td>" + val.nickname +
							"</td><td>" + val.name + "</td><td>" + convertVal(val.phone) + "</td><td>" + typeStr +
							"</td><td>" + statusStr + "</td><td><div style='text-overflow:ellipsis; overflow:hidden; white-space:nowrap; width: 300px;'>"
							+ convertVal(val.remark) + "</div></td><td>" + btn + "</td></tr>";
					});
					$(".userList .tableList").empty().append(html);
					replaceNull($(".userList .tableList"));
				} else {
					layer.msg(res.msg);
					return;
				}
			},
			error: function(res) {
				layer.msg("请求失败，请稍后再试！");
				layer.close(loading);
				return;
			},
			complete: function(XMLHttpRequest, status) {
				if(status == 'timeout') {
					layer.msg("请求超时，请稍后再试！");
					layer.close(loading);
					return;
				}

			}
		});

	}

	//加载订阅公司记录
	function loadSubOrigin(option, url, type) {
		var loading = layer.load(1);
		$.ajax({
			type: "post",
			url: url,
			async: true,
			dataType: 'json',
			timeout: 5000,
			data: option,
			success: function(res) {
				layer.close(loading);
				if(res.code == 0 && res.data != null && res.data.length > 0) {
					var data = res.data;
					var html = '';
					if (type == 1) {
						//早报订阅
						$.each(data, function (index, val) {
							var btn = '';
							if (val.status == 0)
								btn = '已订阅';
							else
								btn = "<a href='javascript:void(0)' data-orgName='" +val.originName + "' data-orgId='" + val.id
									+ "' class='layui-btn btn-addOrgSub'>订阅</a>";
							html += '<tr><td>' + val.originName + '</td><td>' + btn + '</td></tr>';
						});
						$('.orgSubList .tableList').html(html);
					} else if (type == 2) {
						//添加GPS预警订阅
						$.each(data, function (index, val) {
							var btn = '';
							if (val.status == 0)
								btn = '已订阅';
							else
								btn = "<a href='javascript:void(0)' data-orgName='" +val.originName + "' data-orgId='" + val.id
									+ "' class='layui-btn btn-addOrgSub'>订阅</a>";
							html += '<tr><td>' + val.originName + '</td><td>' + btn + '</td></tr>';
						});
						$('.orgGpsSubList .tableList').html(html);
					}
				} else {
					layer.msg(res.msg);
					return;;
				}
			},
			error: function(res) {
				layer.msg("请求失败，请稍后再试！");
				layer.close(loading);
				return;
			},
			complete: function(XMLHttpRequest, status) {
				if(status == 'timeout') {
					layer.msg("请求超时，请稍后再试！");
					layer.close(loading);
					return;
				}

			}
		});
	}


	//订阅早报
	function saveSubscribe(options, url, type) {
		var loading = layer.load(1);
		$.ajax({
			type: "put",
			url: url,
			async: true,
			dataType: 'json',
			timeout: 5000,
			data: options,
			success: function(res) {
				layer.close(loading);
				// console.log(res);
				if(res.code == 0) {
					layer.msg(res.msg);
					if (type == 1) {
						var option = {uid:uid,type:stype};
						loadSubOrigin(option, "/report/subscribe/origin", 1);
					} else if (type == 2) {
						var option = {uid:uid,type:stype};
						loadSubOrigin(option, "/gps/waring/origin", 2);
					}
				} else {
					layer.msg(res.msg);
					return;;
				}
			},
			error: function(res) {
				layer.msg("请求失败，请稍后再试！");
				layer.close(loading);
				return;
			},
			complete: function(XMLHttpRequest, status) {
				if(status == 'timeout') {
					layer.msg("请求超时，请稍后再试！");
					layer.close(loading);
					return;
				}

			}
		});
	}

	//用户状态修改
	function updateUser(options, url) {
		var loading = layer.load(1);
		$.ajax({
			type: "put",
			url: url,
			async: true,
			dataType: 'json',
			timeout: 5000,
			data: options,
			success: function(res) {
				layer.close(loading);
				// console.log(res);
				if(res.code == 0) {
					layer.msg(res.msg);
					if($(".updateModal").show()){
						$(".updateModal").hide();
						$(".updateModal input").val("");
					}
					loadData(tempOptions);
				} else {
					layer.msg(res.msg);
					return;;
				}
			},
			error: function(res) {
				layer.msg("请求失败，请稍后再试！");
				layer.close(loading);
				return;
			},
			complete: function(XMLHttpRequest, status) {
				if(status == 'timeout') {
					layer.msg("请求超时，请稍后再试！");
					layer.close(loading);
					return;
				}

			}
		});
	}

	/**加载部门信息**/
	function loadOrigin(options) {
		var loading = layer.load(1);
		$.ajax({
			type: "post",
			url: '/sys_user/query/origin',
			async: true,
			dataType: 'json',
			timeout: 5000,
			data: options,
			success: function(res) {
				layer.close(loading);
				// console.log(res);
				if(res.code == 0) {
					if($(".updateModal").show()){
						$(".updateModal").hide();
						$(".updateModal input").val("");
					}
					var data = res.data;
					loadOriginData(data);
				} else {
					layer.msg(res.msg);
					return;;
				}
			},
			error: function(res) {
				layer.msg("请求失败，请稍后再试！");
				layer.close(loading);
				return;
			},
			complete: function(XMLHttpRequest, status) {
				if(status == 'timeout') {
					layer.msg("请求超时，请稍后再试！");
					layer.close(loading);
					return;
				}

			}
		});
	}

	/**组装部门信息数据**/
	function loadOriginData(data) {
		if(data == null || data.length <= 0) {
			$(".concatModal .userAndOriginList .tableList").empty().append("<tr><td colspan='4'>暂无数据</td></tr>");
			return;
		}
		var html = '';
		$.each(data, function(index, val) {
			var statusText = "";
			var btn = "";
			if (val.status == 0) {
				statusText = '已关联';
				btn = "<a href='javascript:void(0)' data-uid='" + uid + "' data-id='" + val.id + "' class='layui-btn btn-delConcat'>删除关联</a>";
			} else {
				btn = "<a href='javascript:void(0)' data-uid='" + uid + "' data-id='" + val.id + "' class='layui-btn btn-addConcat'>添加关联</a>";
			}
			html += "<tr><td>" + val.originName +
				"</td><td>" + convertOrigin(val.pid, val.type) + "</td><td>" + statusText + "</td><td>" + btn + "</td></tr>";
		});
		$(".concatModal .userAndOriginList .tableList").empty().append(html);
		replaceNull($(".concatModal .userAndOriginList .tableList"));
	}

	/**加载推送消息订阅类型**/
	function subscribeData(options, url) {
		var loading = layer.load(1);
		$.ajax({
			type: "post",
			url: url,
			async: true,
			dataType: 'json',
			timeout: 5000,
			data: options,
			success: function(res) {
				// console.log(res)
				layer.close(loading);
				if(res.code == 0 && res.data != null) {
					var data = res.data;
					var html = '';
					$.each(data, function (index, val) {
						if (val.name.indexOf('月报') == -1) {
							// if (val.id < 50) {
								var btn = "<a href='javascript:void(0)' data-id='" + val.id + "' class='layui-btn btn-addSub'>订阅</a>";
								html += '<tr><td>' + val.name + '</td><td>' + btn + '</td></tr>';
							// }
							// else if (val.id > 20) {
							// 	var btn = "<a href='javascript:void(0)' data-id='" + val.id + "' class='layui-btn btn-addGpsSub'>订阅</a>";
							// 	html += '<tr><td>' + val.name + '</td><td>' + btn + '</td></tr>';
							// }
						}
					});
					$('.subscribeList .tableList').html(html);
				} else {
					layer.msg(res.msg);
					return;
				}
			},
			error: function(res) {
				layer.msg("请求失败，请稍后再试！");
				layer.close(loading);
				return;
			},
			complete: function(XMLHttpRequest, status) {
				if(status == 'timeout') {
					layer.msg("请求超时，请稍后再试！");
					layer.close(loading);
					return;
				}

			}
		});
	}

	/**关联操作**/
	function relationData(options, url) {
		var loading = layer.load(1);
		$.ajax({
			type: "put",
			url: url,
			async: true,
			dataType: 'json',
			timeout: 5000,
			data: options,
			success: function(res) {
				layer.close(loading);
				if(res.code == 0) {
					layer.msg(res.msg);
					loadOrigin(originOptions);
				} else {
					layer.msg(res.msg);
					return;
				}
			},
			error: function(res) {
				layer.msg("请求失败，请稍后再试！");
				layer.close(loading);
				return;
			},
			complete: function(XMLHttpRequest, status) {
				if(status == 'timeout') {
					layer.msg("请求超时，请稍后再试！");
					layer.close(loading);
					return;
				}

			}
		});
	}

	/***初始化部门信息***/
	function initOrigin() {
		$.ajax({
			type: "post",
			url: '/sys_origin/query/origin',
			async: true,
			dataType: 'json',
			timeout: 5000,
			data: options,
			success: function(res) {
				if(res.code == 0) {
					$.each(res.data, function(index, val) {
						parentOrg[val.id] = val.pid;
						org[val.id] = val.originName;
					});
				}
			},
			error: function(res) {
				layer.msg("请求失败，请稍后再试！");
				return;
			},
			complete: function(XMLHttpRequest, status) {
				if(status == 'timeout') {
					layer.msg("请求超时，请稍后再试！");
					return;
				}
			}
		});
	}

	/**转换部门名称**/
	function convertOrigin(id, type) {
		var orgName = '';
		if (type == 1) {
			var pid = parentOrg[id];
			orgName = convertVal(org[id]);
			if (orgName != null && orgName != undefined && orgName != '')
				if (org[pid] != null && org[pid] != undefined && org[pid] != '')
					orgName = org[pid] + ' ==> ' + orgName;
				else
					orgName = convertVal(org[pid]);
		} else {
			orgName = convertVal(org[id]);
		}
		return orgName;
	}

	/**显示值转换**/
	function convertVal(val) {
		if (val == null || val == '' || val == undefined)
			return '';
		else
			return val;
	}

});